package cn.cagurzhan.handler;

import cn.cagurzhan.domain.BaseEntity;
import cn.cagurzhan.common.exception.ServiceException;
import cn.cagurzhan.service.CacheService;
import cn.cagurzhan.utils.ServletUtils;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.http.HttpStatus;
import com.baomidou.mybatisplus.core.handlers.MetaObjectHandler;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.ibatis.reflection.MetaObject;

import java.util.Date;

/**
 * MybatisPlus 字段更新处理器
 * @author Cagur
 * @version 1.0
 */
@Slf4j
public class CreateAndUpdateMetaObjectHandler implements MetaObjectHandler {


    @Override
    public void insertFill(MetaObject metaObject) {
        if(ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity){
            // 设置创建时间
            BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
            Date current = new Date();
            baseEntity.setLogTime(current);
            baseEntity.setDelFlag(0);
        }

    }

    @Override
    public void updateFill(MetaObject metaObject) {
        try {
            if (ObjectUtil.isNotNull(metaObject) && metaObject.getOriginalObject() instanceof BaseEntity) {
                BaseEntity baseEntity = (BaseEntity) metaObject.getOriginalObject();
                Date current = new Date();
                baseEntity.setLogTime(current);
            }
        } catch (Exception e) {
            throw new ServiceException("自动注入异常 => " + e.getMessage(), HttpStatus.HTTP_UNAUTHORIZED);
        }
    }
}
